import 'package:flutter/material.dart';

import 'hero_image_hint_widget.dart';
import 'hero_image_widget.dart';
import 'hero_swiper_image_widget.dart';

/// 默认最多显示9格
const int maxPicGridViewCount = 9;

/// 多图片查看,九宫格显示
class HeroImageGridWidget extends StatelessWidget {
  const HeroImageGridWidget({
    required this.urlImages,
    this.onPageChanged,
    Key? key,
  }) : super(key: key);
  final List<String> urlImages;
  final ValueChanged<int>? onPageChanged;

  @override
  Widget build(BuildContext context) {
    if (urlImages.isEmpty) {
      return SizedBox.shrink();
    }

    Widget widget = LayoutBuilder(builder: (BuildContext c, BoxConstraints b) {
      final double margin = 10;
      final double size = b.maxWidth;
      int rowCount = 3;
      if (urlImages.length == 1) {
        return Padding(
          padding: EdgeInsets.all(margin),
          child: HeroImageWidget(
            urlImages.first,
            // 拼接上index是为了避免同一个页面,图片路径相同时页面奔溃
            heroTag: "${urlImages.first}-0",
          ),
        );
      }
      double totalWidth = size;
      if (urlImages.length == 4) {
        totalWidth = size / 3 * 2;
        rowCount = 2;
      }
      return Container(
        margin: EdgeInsets.all(margin),
        width: totalWidth,
        child: GridView.builder(
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: rowCount,
              crossAxisSpacing: 2.0,
              mainAxisSpacing: 2.0),
          itemBuilder: (BuildContext s, int index) {
            return ImageHintWidget(
              HeroSwiperImageWidget(
                urlImages,
                index: index,
                onPageChanged: onPageChanged,
              ),
            );
          },
          physics: const NeverScrollableScrollPhysics(),
          itemCount: urlImages.length.clamp(1, maxPicGridViewCount),
          padding: const EdgeInsets.all(0.0),
        ),
      );
    });
    widget = Align(
      child: widget,
      alignment: Alignment.centerLeft,
    );
    return widget;
  }
}
